<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                v-for="item in artCateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArticleList()"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          @click="dialogVisible = true"
          type="primary"
          size="small"
          class="btn-pub"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <template>
        <el-table :data="articleList" border style="width: 100%">
          <el-table-column prop="title" label="文章标题" width="180">
            <template #default="{ row }">
              <el-link type="primary" @click="showArtDetail(row.id)">
                {{ row.title }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="cate_name"
            label="文章分类"
            width="180"
          ></el-table-column>
          <el-table-column prop="pub_date" label="发布时间">
            <template #default="{ row }">
              {{ formatDate(row.pub_date) }}
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态"> </el-table-column>
          <el-table-column prop="state" label="操作">
            <template #default="{ row }">
              <el-button type="danger" size="mini" @click="del(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 发布文章的对话框 -->
    <el-dialog
      @close="resetForm"
      title="发表文章"
      :visible.sync="dialogVisible"
      fullscreen
    >
      <el-form
        ref="form"
        :model="articleForm"
        :rules="rules"
        label-width="80px"
      >
        <!-- 文章标题 -->
        <el-form-item label="文章标题" prop="title">
          <el-input
            v-model="articleForm.title"
            placeholder="请输入文章标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章分类" width="100%" prop="cate_id">
          <el-select
            v-model="articleForm.cate_id"
            placeholder="请选择文章分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in artCateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 文章内容 -->
        <el-form-item label="文章内容" prop="content">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="articleForm.content"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img
            src="../../../assets/images/cover.jpg"
            alt=""
            class="cover-img"
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFile"
            @change="chooseImg"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <!-- 发布和草稿按钮 -->
        <el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')"
            >发布</el-button
          >
          <el-button type="info" @click="pubArticle('草稿')"
            >存储草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 显示文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailDialog" width="80%">
      <h1 class="title">{{ detail.title }}</h1>

      <div class="info">
        <span> 作者：{{ detail.nickname || detail.username }} </span>
        &nbsp;<span> 发布时间： {{ formatDate(detail.pub_date) }} </span>
        &nbsp;<span> 所属分类：{{ detail.cate_name }} </span> &nbsp;<span>
          状态：{{ detail.state }}
        </span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <img
        :src="'http://big-event-vue-api-t.itheima.net' + detail.cover_img"
        alt=""
      />

      <div v-html="detail.content"></div>
    </el-dialog>
  </div>
</template>


<script>
import defaultImg from "@/assets/images/cover.jpg";
import dayjs from "dayjs";
export default {
  name: "ArtList",
  created() {
    // 时间格式化函数
    this.formatDate();
    // 获取文章列表的数据
    this.getArticleList();
    // 获取表单分类的数据
    this.getArtCate();
  },
  data() {
    return {
      detailDialog: false,
      // 存储文章根据id获取的详情数据
      detail: {},
      // 保存文章的数量
      total: 0,
      // 保存获取的文章列表的数据
      articleList: [],
      // 存储获取的文章分类的数据
      artCateList: [],
      // 收集表单的数据对象
      articleForm: {
        title: "",
        cate_id: "",
        content: "",
        state: "",
        cover_img: null, //保存封装对象
      },
      // 控制发表文章的对话框的显示和隐藏
      dialogVisible: false,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: "",
      },
      // 校验规则
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            pattern: /^\S{1,30}$/,
            message: "文章名称必须是1-30位的字符",
            trigger: "blur",
          },
        ],
        cate_id: [
          { required: true, message: "请选择文章分类", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 根据id进行删除操作
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("/my/article/info", {
            params: { id },
          });
          console.log(res, "deldeldel");
          if (res.code !== 0) return this.$message.error(res.message);
          this.$message.success(res.message);
          // 重新渲染
          if (this.articleList.length === 1) {
            this.q.pagenum--;
          }
          this.getArticleList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取文章详情的数据
    async showArtDetail(id) {
      console.log(id, "ididididid");
      const { data: res } = await this.$http.get("/my/article/info", {
        params: { id },
      });
      console.log(res, "showArtDetail");
      if (res.code !== 0) return this.$message.error("获取文章详情失败!");
      this.detail = res.data;
      // 显示对话框
      this.detailDialog = "";
    },
    // 重置
    reset() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: "",
      };
      this.getArticleList();
    },
    // 修改一页显示的条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      // 保证每次切换时都会回到第一页,而不是当前条
      this.q.pagenum = 1;
      this.q.pagesize = val;
      this.getArticleList();
    },
    // 修改当前页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.q.pagenum = val;
      this.getArticleList();
    },
    // 时间格式化函数
    formatDate(time) {
      return dayjs(time).format("YYYY-MM-DD HH-mm-ss");
    },
    // 关闭对话框时重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.articleForm.cover_img = null;
      // 将图片预览区更改为默认浏览
      this.$refs.imgRef.setAttribute("src", defaultImg);
      // 将状态改成已发布
    },
    /* 获取文章列表
    1.发送请求
    2.在data函数中存储数据
    3.渲染表格
    */
    async getArticleList() {
      const { data: res } = await this.$http.get("/my/article/list", {
        params: this.q,
      });
      console.log(res, "getArticleList");
      this.articleList = res.data;
      this.total = res.total;
    },
    // 发布文章,设置状态
    pubArticle(state) {
      // 设置文章的发布状态
      this.articleForm.state = state;
      //  关闭对话框
      this.dialogVisible = false;
      //   1.兜底校验
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        // 无prop的单独校验
        if (this.articleForm.cover_img === null)
          return this.$message.error("请上传封面图片!");
        /* 
        转换为formData,因为有对象
        */
        const fd = new FormData();
        Object.keys(this.articleForm).forEach((key) =>
          fd.append(key, this.articleForm[key])
        );
        // 发送请求
        const { data: res } = await this.$http.post("/my/article/add", fd);
        console.log(res.data, "pubArticle");
        // 判断请求是否成功
        if (res.code !== 0) return this.$message.error(res.message);
        // 3.1 发布失败
        if (res.code !== 0) return this.$message.error("发布失败");
        // 3.2 发布成功提示用户
        if (state == "已发布") {
          this.$message.success(res.message);
        } else {
          this.$message.success("草稿储存成功!");
        }
        // 关闭对话框
        this.dialogVisible = false;
        // 发送请求获取数据渲染页面
        this.getArticleList();
      });
    },
    // 选择图片
    chooseImg(e) {
      const files = e.target.files;
      console.log(files, "files");
      if (files.length !== 0) {
        // 讲数据存储到表单的数据对象中
        this.articleForm.cover_img = files[0];
        // 将文件对象转化为图片地址
        const url = URL.createObjectURL(files[0]);
        // 设置标签的属性值
        this.$refs.imgRef.setAttribute("src", url);
        this.$refs.iptFile.value = "";
      } else {
        this.articleForm.cover_img = null;
        this.$refs.imgRef.setAttribute("src", defaultImg);
      }
    },
    // 获取表单分类的数据
    async getArtCate() {
      const { data: res } = await this.$http.get("/my/cate/list");
      console.log(res.data, "getArtCate");
      this.artCateList = res.data;
    },
  },
};
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
</style>
